Ext.namespace("Dudley");
Ext.namespace("Dudley.lims");

Dudley.lims.KruglyakCrossing = function() {

    var myCrossingData = [];
    var kruglyakForm = {};
    var kruglyakPanel = {};
    var kruglyakHash = null;
    var kruglyakCount = null;
    var kruglyakMaxNum = null;
    var kruglyakStore = null;
    var kruglyakLoaded = false;

    function initKruglyakStore(failedCb, callback) {
        loadCrossingSearchResult(0, null, callback);
    }

    function loadCrossingSearchResult(index, searchResultJSON, callback) {
   	    kruglyakStore = loadSolrSearchResult("YKR", getCrossingPagingColumns(), crossingSolrTranslator, index, searchResultJSON);
        kruglyakStore.load({params:{start:0, limit:25}}, callback());
    }

    function goSearch(index, kruglyakSearchInput, kruglyakSearchOption) {
       if (kruglyakSearchInput == "") {
                        kruglyakSearchInput = 'YKR*';
         }
         var searchUrl = getSolrSearchUrl(getLuceneTerm("ycrFields",kruglyakSearchInput), 1000, ycrFields);
         var searchWin = getSearchLoadingWindow("ykr-");
         searchWin.on("show", function () {
            var sb = Ext.getCmp("ykr-search-statusbar");
            sb.showBusy();
        });
        searchWin.show();
        Ext.Ajax.request({
            url: searchUrl,
            method: "GET",
            success: function(response) {
                var searchResultObj = Ext.util.JSON.decode(response.responseText);
                eventManager.fireStatusMessageEvent({ text: "Crossing Search Results Count:" + searchResultObj.response.numFound, level: "info" });
                loadCrossingSearchResult(index, searchResultObj.response, function() {
                    Ext.getDom("sample-search-result-list").innerHTML = "";
                    Ext.getDom("yo-form").innerHTML = "";
                    searchWin.close();
                    renderCrossingSearchResult();
                });
            },
            failure: function() {
                eventManager.fireStatusMessageEvent({ text: "Search Results failed for url:" + searchUrl, level: "error" });
            }
        });
     /*   kruglyakSearchInput = kruglyakSearchInput + "";
        kruglyakSearchInput = kruglyakSearchInput.replace(/ykr /, "YKR ");
        kruglyakSearchInput = kruglyakSearchInput.replace(/Ykr /, "YKR ");
        kruglyakSearchInput = kruglyakSearchInput.replace(/ykR /, "YKR ");
        kruglyakSearchInput = kruglyakSearchInput.replace(/YkR /, "YKR ");
        kruglyakSearchInput = kruglyakSearchInput.replace(/ /g, "%20");
        var freeSearchOp = "FREE_TEXT=" + kruglyakSearchInput;
        var matchingAllTerms = "MATCHING_ALL_TERMS=true";
        var matchingSearchHash = "";
        if (kruglyakSearchOption == null || kruglyakSearchOption == 'All' || kruglyakSearchOption == '') {
            matchingAllTerms = "";
            if (kruglyakSearchInput == '') {
                kruglyakSearchInput = '*';
            }
        } else {
            freeSearchOp = "";
            matchingSearchHash = "&" + kruglyakSearchOption + "=" + kruglyakSearchInput;
        }
        var searchUrl = getKruglyakSearchUrl(freeSearchOp, matchingAllTerms, matchingSearchHash);
        var searchWin = new Ext.Window({
            title: 'Kruglyak Crossing',
            width: 400,
            minWidth: 350,
            height: 150,
            modal: true,
            closeAction: 'hide',
            bodyStyle: 'padding:10px;',
            html: "Loading Kruglyak Crossings...",
            bbar: new Ext.ux.StatusBar({
                id: 'search-kruglyak-statusbar',
                defaultText: 'Ready'
            })
        });
        searchWin.on("show", function () {
            var sb = Ext.getCmp("search-kruglyak-statusbar");
            sb.showBusy();
        });
        searchWin.show();
        Ext.Ajax.request({
            url: searchUrl,
            method: "GET",
            success: function(response) {
                var searchResultObj = Ext.util.JSON.decode(response.responseText);
                eventManager.fireStatusMessageEvent({ text: "Crossing Search Results Count:" + searchResultObj.numberOfResults, level: "info" });
                myCrossingData = [];
                loadCrossingSearchResult(index, searchResultObj, function() {
                    Ext.getDom("sample-search-result-list").innerHTML = "";
                    Ext.getDom("yo-form").innerHTML = "";
                    searchWin.close();
                    renderCrossingSearchResult();
                });
            },
            failure: function() {
                eventManager.fireStatusMessageEvent({ text: "Search Results failed for url:" + searchUrl, level: "error" });
            }
        });*/

    }

    function loadCrossingPanel() {
        var kruglyakSearchForm = getSearchForm("kruglyakSearchButtonId", "kruglyakSearchInputId", null);
                Ext.getCmp("kruglyakSearchButtonId").addListener("click", function(){
            			goSearch(0, Ext.getCmp("kruglyakSearchInputId").getValue(), "ycrFields");
            	   });
                        var tbarButtons = [
            {
                id: 'showCrossingSearchResultsId',
                name: 'showCrossingSearchResults',
                disabled: true,
                text: '<--Search Results',
                icon: "images/back-green.png",
                cls:'x-btn-text-icon',
                listeners: {click:
                        function() {
                            Ext.getDom("yo-form").innerHTML = "";
                            renderCrossingSearchResult();
                        }
                }
            },
            {
                id: 'searchAllCrossingId',
                name: 'searchAllCrossing',
                disabled: false,
                text: 'View All Records',
                icon: "images/search-blue.png",
                cls:'x-btn-text-icon',
                listeners: {click:
                        function() {
                            Ext.getDom("yo-form").innerHTML = "";
                            goSearch(0, 'YKR', 'ycrKey');
                        }
                }
            }
        ];
        kruglyakPanel = new Ext.Panel({
            id: "kruglyakPanelId",
            autoHeight: true,
            border: true,
            renderTo: "yad-panel",
            title: "Kruglyak",
            header: false,
            tbar: tbarButtons,
            items: kruglyakSearchForm
        });
        kruglyakPanel.on("activate", function () {
            Ext.getDom("yo-panel").innerHTML = "";
            Ext.getDom("yo-form").innerHTML = "";
            Ext.getDom("sample-search-result-list").innerHTML = "";
            if (kruglyakLoaded == false) {
                kruglyakLoaded = true;
                goSearch(0, 'YKR', 'ycrKey');
            }
            renderCrossingSearchResult();
        });
    }

    function postCrossingStrain(createNew) {
        var ycrKey = Ext.getCmp("crossingKeyId").getValue();
        var ycrPostJson = new Object();
        ycrPostJson["ycrKey"] = ycrKey;
        ycrPostJson["ycrAlias"] = Ext.getCmp("crossingAliasId").getValue();
        ycrPostJson["ycrParentA"] = Ext.getCmp("parentAId").getValue();
        ycrPostJson["ycrParentAlpha"] = Ext.getCmp("parentAlphaId").getValue();
        ycrPostJson["ycrProgenyCt"] = Ext.getCmp("progenyCountId").getValue();
        ycrPostJson["ycrProgenyRange"] = Ext.getCmp("progenyRangeId").getValue();
        ycrPostJson["ycrDate"] = Ext.getCmp("crossingDateId").getRawValue();
        ycrPostJson["ycrPlates"] = Ext.getCmp("crossingPlatesId").getRawValue();
        ycrPostJson["ycrNotes"] = Ext.getCmp("crossingNoteId").getRawValue();
        var crossingCallback = function() {
                limsadmin_obj["limsadminCrossingCount"] = crossingCount;
                postSolrUpdates(limsadmin_obj, function(){
                    Ext.Msg.alert('Info', "New Crossing " + ycrKey + ' Added Successfully');
                    Ext.getDom("yo-form").innerHTML = "";
                    Ext.getDom("sample-search-result-list").innerHTML = "";
                    goSearch(0, ycrKey, "ycrKey");
                });
            };
            if (!createNew) {
                crossingCallback = function() {
                    Ext.Msg.alert('Info', ycrKey + ' Updated Successfully');
                    Ext.getDom("sample-search-result-list").innerHTML = "";
                    var searchResultsButton = Ext.getCmp("showCrossingSearchResultsId");
                    searchResultsButton.disable();
                };
            }
            postSolrUpdates(ycrPostJson, crossingCallback);
    }

    /*function postCrossingStrain(createNew) {
        var ycrKey = Ext.getCmp("crossingKeyId").getValue();
        var ycrPostJson = new Object();
        ycrPostJson["key"] = ycrKey;
        ycrPostJson["crossingAlias"] = Ext.getCmp("crossingAliasId").getValue();
        ycrPostJson["parentA"] = Ext.getCmp("parentAId").getValue();
        ycrPostJson["parentAlpha"] = Ext.getCmp("parentAlphaId").getValue();
        ycrPostJson["progenyCount"] = Ext.getCmp("progenyCountId").getValue();
        ycrPostJson["progenyRange"] = Ext.getCmp("progenyRangeId").getValue();
        ycrPostJson["crossingDate"] = Ext.getCmp("crossingDateId").getRawValue();
        ycrPostJson["crossingPlates"] = Ext.getCmp("crossingPlatesId").getRawValue();
        ycrPostJson["crossingNote"] = Ext.getCmp("crossingNoteId").getRawValue();
        var strainOp = "create";
        var ycrCallback = function() {
            var ycrAnnoJson = new Object();
            ycrAnnoJson['crossingMaxNum'] = kruglyakMaxNum;
            ycrAnnoJson['crossingCount'] = kruglyakCount;
            postDudleyAnnotations('/addama-rest/dudley-sample/path/datasource/YKR/annotations', ycrAnnoJson, function() {
                eventManager.fireStatusMessageEvent({ text: "New YKR Strain Added Successfully", level: "info" });
                Ext.Msg.alert('Info', "New YKR " + ycrKey + ' Added Successfully');
                Ext.getDom("yo-form").innerHTML = "";
                goSearch(0, ycrKey, "key");
            });
        };
        if (!createNew) {
            strainOp = "annotations";
            ycrCallback = function() {
                Ext.Msg.alert('Info', ycrKey + ' Updated Successfully');
                var searchResultsButton = Ext.getCmp("showCrossingSearchResultsId");
                searchResultsButton.disable();
            };
        }
        var ycrPostUrl = "/addama-rest/dudley-sample/path/datasource/YKR/" + ycrKey + "/" + strainOp;
        postDudleyAnnotations(ycrPostUrl, ycrPostJson, ycrCallback);
    } */

    function loadCreateCrossingStrain(kruglyakHash, callback) {
        var createNew = true;
        var buttons = [
            {
                id: 'createButton',
                name: 'createButton',
                text: 'Create',
                listeners: {click:
                        function() {
                            if (validateCreateUpdateCrossing()) {
                                postCrossingStrain(createNew);
                            }
                        }
                }
            }
        ];
        if (kruglyakHash != null) {
            if (kruglyakHash.genotype != undefined && kruglyakHash.genotype == 'Record Deleted') {
                buttons = [];
            } else {
                var viewProg = true;
                if (kruglyakHash.progenyCount != null && kruglyakHash.progenyCount != 0) {
                    viewProg = false;
                }
                buttons = [
                    {
                        id: 'updateCrossingButtonId',
                        name: 'updateCrossingButton',
                        text: 'Update',
                        listeners: {click:
                                function() {
                                    if (validateCreateUpdateCrossing()) {
                                        postCrossingStrain(!createNew);
                                    }
                                }
                        }
                    }
                ];
            }
        } else {
            kruglyakHash = new Object();
            var kruglyakMaxInt = parseInt(kruglyakMaxNum);
            kruglyakMaxInt = kruglyakMaxInt + 1;
            var kruglyakCountInt = parseInt(kruglyakCount);
            kruglyakCountInt = kruglyakCountInt + 1;
            kruglyakCount = kruglyakCountInt + "";
            kruglyakHash.name = 'YKR' + kruglyakMaxInt;
            kruglyakMaxNum = kruglyakMaxInt + "";
        }

        if (kruglyakHash.kruglyakNote == null) {
            kruglyakHash.kruglyakNote = "";
        }
        if (kruglyakHash.progenyCount == null) {
            kruglyakHash.progenyCount = 0;
        }
        if (kruglyakHash.kruglyakPlates == null) {
            kruglyakHash.kruglyakPlates = "";
        }

        kruglyakForm = new Ext.form.FormPanel({
            id: 'kruglyakForm',
            method: 'POST',
            autoHeight: true,
            autoScroll: true,
            border: true,
            buttonAlign: 'left',
            tbar: [
                {
                    id: 'viewKruglyakProgenyButtonId',
                    text: 'View Progeny',
                    disabled: !createNew,
                    icon: "images/star.png",
                    cls:'x-btn-text-icon',
                    tooltip: 'View progeny',
                    listeners: {click:
                            function() {
                                Dudley.lims.YPGStrain.setSearchParam(kruglyakHash.name.replace(/ /, ""));
                                Dudley.lims.YPGStrain.setSearchOption("ypgCrossingRef");
                                //Dudley.lims.YPGStrain.setSearchParam(kruglyakHash.name);
                                //Dudley.lims.YPGStrain.setSearchOption("crossingRef");
                                Dudley.lims.YPGStrain.setYPGLoaded(false);
                                var ypgPanel = Dudley.lims.YPGStrain.getYPGPanelInst();
                                Dudley.lims.samplemgr.getHousingPanel().activate(ypgPanel);
                            }
                    }
                }
            ],
            buttons: buttons,
            items: [
                new Ext.form.FieldSet({
                    autoHeight: true,
                    border: false,
                    items: [
                        new Ext.form.TextField({
                            id: "crossingKeyId",
                            fieldLabel: "Key",
                            name: "kruglyakKey",
                            value: kruglyakHash.name,
                            width: 500,
                            readOnly: true,
                            allowBlank: false
                        }),
                        new Ext.form.TextField({
                            id: "crossingAliasId",
                            fieldLabel: "Alias",
                            name: "kruglyakAlias",
                            value: kruglyakHash.crossingAlias,
                            width: 500,
                            allowBlank: false
                        }),
                        new Ext.form.TextField({
                            id: "parentAId",
                            fieldLabel: "Parent A",
                            name: "parentA",
                            value: kruglyakHash.parentA,
                            width: 500,
                            allowBlank: false
                        }),
                        new Ext.form.TextField({
                            id: "parentAlphaId",
                            fieldLabel: "Parent Alpha",
                            name: "parentAlpha",
                            value: kruglyakHash.parentAlpha,
                            width: 500,
                            allowBlank: false
                        }),
                        new Ext.form.TextField({
                            id: "progenyCountId",
                            fieldLabel: "Progeny Count",
                            name: "progenyCount",
                            value: kruglyakHash.progenyCount,
                            width: 500,
                            allowBlank: false
                        }),
                        new Ext.form.TextField({
                            id: "progenyRangeId",
                            fieldLabel: "Progeny Range",
                            name: "progenyRange",
                            value: kruglyakHash.progenyRange,
                            width: 500,
                            allowBlank: false
                        }),

                        new Ext.form.DateField({
                            id: "crossingDateId",
                            fieldLabel: "Crossing Date",
                            name: "kruglyakDate",
                            value: kruglyakHash.crossingDate,
                            size: 20,
                            allowBlank: true
                        }),
                        {
                            xtype:'htmleditor',
                            id:'crossingPlatesId',
                            value: kruglyakHash.crossingPlates,
                            fieldLabel:'Plates and Parents Position',
                            height:130,
                            anchor:'98%',
                            listeners: {
                                activate: function(e) {
                                    if (kruglyakHash.kruglyakPlates == undefined || kruglyakHash.kruglyakPlates == "") {
                                        e.execCmd('delete');
                                    }
                                }
                            }
                        },
                        {
                            xtype:'htmleditor',
                            id:'crossingNoteId',
                            value: kruglyakHash.crossingNote,
                            fieldLabel:'Comments ' + '<br><i><font size=-2>Relevant information about the cross not covered in other fields</font></i>',
                            height:100,
                            anchor:'98%',
                            listeners: {
                                activate: function(e) {
                                    if (kruglyakHash.kruglyakNote == undefined || kruglyakHash.kruglyakNote == "") {
                                        e.execCmd('delete');
                                    }
                                }
                            }
                        }
                    ]
                })
            ]
        });
        callback();
    }

    function viewCrossingProgeny(kruglyakKey) {
        Dudley.lims.YPGStrain.renderYPG(kruglyakKey);
    }

    function renderCrossingSearchResult() {
        Ext.getDom("yo-panel").innerHTML = "";
        Ext.getDom("yad-panel").innerHTML = "";

        Ext.getDom("yo-form").innerHTML = "";

        var searchResultsButton = Ext.getCmp("showCrossingSearchResultsId");
        if (searchResultsButton != null || searchResultsButton != undefined) {
            searchResultsButton.disable();
        }

        var searchResultsGrid = new Ext.grid.GridPanel({
            id: "kruglyakSearchResultsId",
            store: kruglyakStore,
            columns: getCrossingSearchColumnHeaders(),
            stripeRows: true,
            autoHeight: true,
            width: 750,
            title: 'Crossing',
            renderTo: "sample-search-result-list",
            tbar: [
                {
                    id: 'kcrossing2CSVId',
                    text: 'Export2CSV',
                    icon: "images/check-green.png",
                    cls:'x-btn-text-icon',
                    tooltip: 'Export search results to csv',
                    listeners: {click:
                            function() {
                                Dudley.lims.Crossing.toCSV(myCrossingData, "YKRSearchedResults.csv");
                            }
                    }
                }
            ],
            bbar: new Ext.PagingToolbar({
                pageSize: 20,
                store: kruglyakStore,
                displayInfo: true,
                displayMsg: 'Displaying strains {0} - {1} of {2}',
                emptyMsg: "No strains to display"
            })
        });
        searchResultsGrid.on("celldblclick", function (g, ri, ci, e) {
            var searchResultsButton = Ext.getCmp("showCrossingSearchResultsId");
            searchResultsButton.enable();
            kruglyakHash = new Object();
            populateCrossingJson(kruglyakHash, g);
            
            loadCreateCrossingStrain(kruglyakHash, function() {
                kruglyakFormRender();
            });
        });
    }

    function kruglyakFormRender() {
        Dudley.lims.samplemgr.getHousingPanel().activate(kruglyakPanel);
        Ext.getDom("sample-search-result-list").innerHTML = "";
        Ext.getDom("yo-form").innerHTML = "";
        kruglyakForm.render("yo-form");
    }

    // public
    return {
        initKruglyak: function(failedCB) {
            initKruglyakStore(failedCB, function() {
                eventManager.fireStatusMessageEvent({ text: "Finishing init Crossing Store", level: "info" });
            });
        },

        getKruglyakPanel: function() {
            loadCrossingPanel();
            return kruglyakPanel;
        },

        getKruglyakStore: function() {
            return kruglyakStore;
        },

        loadNewKruglyak: function() {
            Ext.getDom("yo-form").innerHTML = "";
            
            Ext.Ajax.request({
                url: "/addama-rest/dudley-sample/path/datasource/YKR/annotations",
                method: "GET",
                success: function(response) {
                    var yoAnnoObj = Ext.util.JSON.decode(response.responseText);
                    kruglyakCount = yoAnnoObj.kruglyakCount;
                    kruglyakMaxNum = yoAnnoObj.kruglyakMaxNum;
                    kruglyakHash = null;
                    var searchResultsButton = Ext.getCmp("showCrossingSearchResultsId");
                    searchResultsButton.enable();
                    loadCreateCrossingStrain(kruglyakHash, function() {
                        Ext.getDom("sample-search-result-list").innerHTML = "";
                        Ext.getDom("yo-form").innerHTML = "";
                        kruglyakForm.render("yo-form");
                    });
                },
                failure: function() {
                    eventManager.fireStatusMessageEvent({ text: "Failed Getting Annotations for Crossing Datasource", level: "error" });
                }
            });

        },
        loadSearchResult: function() {
            Ext.getDom("sample-search-result-list").innerHTML = "";
            renderCrossingSearchResult();
        },
         setArrayData: function(data) {
            myCrossingData = data;
         }
    };
}();
